package servlet;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.UUID;

@WebServlet(name = "ImageUploadServlet", urlPatterns = "/upload")
@MultipartConfig
public class ImageUploadServlet extends HttpServlet {
    private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI5tNcXzSbJg7RMFaskqWU";
    private static final String ACCESS_KEY_SECRET = "Cfnn3JEwevJby29P1gY5gzqSoCg48t";
    private static final String BUCKET_NAME = "wdwc2";

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Part filePart = request.getPart("pimage");
        //System.out.println("image   --------" + filePart.getSubmittedFileName());
        String fileName = UUID.randomUUID() + "_" + filePart.getSubmittedFileName();

        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, fileName, filePart.getInputStream());
        ossClient.putObject(putObjectRequest);
        ossClient.shutdown();
        // 写回json
        System.out.println("{\"imageUrl\":\"" + "https://" + BUCKET_NAME + "." + ENDPOINT + "/" + fileName + "\"}");
        response.getWriter().write("{\"imageUrl\":\"" + "https://" + BUCKET_NAME + "." + ENDPOINT + "/" + fileName + "\"}");
    }
}
